const util = require('../../../utils/util.js');
const api = require('../../../config/api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orders: [],
    status: -1,
    page: 1,
    pageSize: 10,
    hasMore: false
  },
  tabBox(e) {
    this.setData({
      orders: [],
      status: e.currentTarget.dataset.index,
      page: 1
    });
    this.selectOrders();
  },
  selectOrders: function() {
    let that = this;
    util.request(api.SelectOrderSUrl, {
      type: that.data.status,
      pageIndex: that.data.page,
      pageSize: that.data.pageSize
    }).then(function(res) {
      if (res.success) {
        if (that.data.page <= res.data.pages) {
          let list = that.data.orders.concat(res.data.list);
          that.setData({
            orders: list,
            hasMore: true,
            page: that.data.page + 1
          });
        } else {
          that.setData({
            hasMore: false
          });
        }
      }
    });
  },
  onLoad: function(options) {
    if (options.type) {
      this.setData({
        status: options.type
      });
    }
  },
  onShow: function() {
    this.selectOrders();
  },
  onReachBottom: function() { //上拉触发需顶层的display：flex去掉
    console.log('onPullDownRefresh');
    if (this.data.hasMore) {
      // 显示加载图标  
      wx.showLoading({
        title: '玩命加载中',
      })
      this.selectOrders();
      // 隐藏加载框  
      wx.hideLoading();
    } else {
      wx.showToast({
        title: '没有更多数据'
      })
    }
  },
  toPay: function(event) {
    let that = this;
    util.request(api.ToPayUrl, {
      orderId: event.currentTarget.dataset.oid,
      payType: 1,
      payMoney: event.currentTarget.dataset.total
    }).then((res) => {
      if (res.success) {
        const payParam = res.data;
        wx.requestPayment({
          'timeStamp': payParam.timeStamp,
          'nonceStr': payParam.nonceStr,
          'package': payParam.package,
          'signType': payParam.signType,
          'paySign': payParam.paySign,
          'success': function(res) {
            that.result('支付成功', that);
          },
          'fail': function(res) {
            that.result('支付失败', that);
          }
        });
      } else {
        that.result(res.message, that);
      }
    });
  },
  toCancel: function(event) {
    let that = this;
    util.request(api.ToCancelUrl, {
      oid: event.currentTarget.dataset.oid
    }).then(function(res) {
      that.result(res.message, that);
    });
  },
  toFinish: function(event) {
    let that = this;
    util.request(api.ToFinishUrl, {
      oid: event.currentTarget.dataset.oid
    }).then(function(res) {
      that.result(res.message, that);
    });
  },
  toComments: function(event) {

  },
  toRefund: function(event) {

  },
  result: function(msg, that) {
    wx.showToast({
      title: msg
    })
    that.setData({
      orders: [],
      page: 1
    });
    that.onShow();
  }
})